package com.jeremyfeinstein.utils;

import android.os.Handler;
import android.os.Looper;

/**
 * Created by sunxunchao on 2018/4/17.
 */

/**
 * 切换到主线程  UI线程
 */
public class SwitchToMainThread {

    private static SwitchToMainThread instance;

    private Handler mHandler;

    public static SwitchToMainThread getInstance() {
        //if (instance == null) {
           // synchronized (SwitchToMainThread.class) {
                if (instance == null) {
                    instance = new SwitchToMainThread();
                }
            //}
        //}
        return instance;
    }

    private SwitchToMainThread() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    public void post(Runnable runnable) {
        if (isMainThread()) {
            runnable.run();
        } else {
            mHandler.post(runnable);
        }
    }

    public void postDelayed(Runnable runnable, long delayMillis) {
        mHandler.postDelayed(runnable, delayMillis);
    }

    /**
     * 当前线程是否为主线程
     *
     * @return
     */
    public boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }
}
